<template>
  <view class="inbound-detail-container">

    <!-- 商品信息块 -->
    <view class="info-block">
      <view class="block-title">商品信息</view>
      <view class="info-content">
        <view v-for="(item, index) in productInfo" :key="item.rowid">
          <view class="product-item">
            <view class="info-item">
              <text class="info-label">商品名称：</text>
              <text class="info-value">{{ item['689ad8a3f23d51578296dfbc'] }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">商品条码：</text>
              <text class="info-value">{{ item['689ad90af23d51578296e021'] }}</text>
            </view>
     
            <view class="info-item">
              <text class="info-label">保质期：</text>
              <text class="info-value">{{ item['689ad90af23d51578296e023'] }}{{item['689ad90af23d51578296e024']}}</text>
            </view>
         
            <view class="info-item">
              <text class="info-label">计划数量：</text>
              <text class="info-value">{{ item['686f6f52f7607b6cf05f8c9c'] }}</text>
            </view>
          </view>
          <!-- 灰色分割线，除了最后一个商品 -->
          <view v-if="index < productInfo.length - 1" class="product-divider"></view>
        </view>
      </view>
    </view>
    
    <!-- 任务信息块 -->
    <view class="info-block" v-if="taskInfo && Object.keys(taskInfo).length > 0">
      <view class="block-title">任务类型：{{ taskInfo['6864a5824e2949f41199067a'] }}</view>
      <view class="info-content">



        <view class="info-item" v-if="taskInfo['68661ed757603df8e65ceb52'] && taskInfo['68661ed757603df8e65ceb52'].trim() !== ''">
          <text class="info-label">配送仓点：</text>
          <text class="info-value">{{ getWarehouseName(taskInfo['68661ed757603df8e65ceb52']) }}</text>
        </view>


        <view class="info-item">
          <text class="info-label">备注：</text>
          <text class="info-value">{{ taskInfo['68707d4c67415961ee20a9e4'] }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">SKU种数：</text>
          <text class="info-value">{{ taskInfo['68b4fb5e153a1d736d8571f8'] }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">计划总数：</text>
          <text class="info-value">{{ taskInfo['68b4fb7b153a1d736d85720b'] }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">创建人：</text>
          <text class="info-value">{{ getCreatorName(taskInfo) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">创建时间：</text>
          <text class="info-value">{{ taskInfo['68afbcee6b50e0d4f7a7574f'] }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">任务编号：</text>
          <text class="info-value">{{ taskInfo['6864a5824e2949f411990670'] }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">单据上传：</text>
          <text class="info-value">{{ taskInfo.documentUpload || '单据上传 ' }}</text>
        </view>
      </view>
    </view>
    
     <!-- 操作按钮 -->
        <view class="card-actions" v-if="taskInfo && taskInfo['6864a5824e2949f411990679'] == '已下发'">
          <text class="cancel-btn" @click="handleCancel">取消</text>
        </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { callWorkflowAPI, callWorkflowListAPI } from '../../../utils/workflow'
import { useUserStore } from '../../../store/user'
import { useTaskStore } from '../../../store/task'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'
import http from '../../../utils/request'

const userStore = useUserStore()
const taskStore = useTaskStore()

// 商品信息数据
const productInfo = ref([])

// 任务信息数据
const taskInfo = ref({})


// 处理取消按钮点击
const handleCancel = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消该任务吗？',
    success: async (res) => {
      if (res.confirm) {

        await http.post(`https://www.dachen.vip/api/workflow/hooks/${userStore.getWarehouseInfo().gys_rk_cancel}`, {
    "userRowid": userStore.getUserInfo().rowid,
    "cardRowid": taskInfo.value.rowid
    })

        uni.showToast({
          title: '任务已取消',
          icon: 'success'
        })
        // 使用Pinia store设置待处理任务，然后返回
        setTimeout(() => {
          taskStore.setPendingTaskUpdate({ rowid: taskInfo.value.rowid })
          uni.navigateBack()
        }, 1500)
      }
    }
  })
}

// 安全获取创建人姓名
const getCreatorName = (task) => {
  try {
    // 尝试多种可能的数据结构
    if (task && task.caid && task.caid.fullname) {
      return task.caid.fullname
    }
    if (task && task.caid && typeof task.caid === 'string') {
      // 如果caid是字符串，尝试解析JSON
      const parsed = JSON.parse(task.caid)
      return parsed.fullname || ''
    }
    if (task && task.creator) {
      return task.creator
    }
    return '未知'
  } catch (error) {
    console.error('解析创建人数据失败:', error)
    return '未知'
  }
}

// 安全解析配送仓点名称
const getWarehouseName = (warehouseData) => {
  try {
    if (!warehouseData || warehouseData.trim() === '') {
      return ''
    }
    const parsed = JSON.parse(warehouseData)
    return parsed && parsed[0] && parsed[0].name ? parsed[0].name : ''
  } catch (error) {
    console.error('解析配送仓点数据失败:', error)
    return ''
  }
}

const getProductInfo = async (rowidList) => {
   const filters = [
    {
      "controlId": "rowid",
      "dataType": 2,
      "spliceType": 1,
      "filterType": 2,
      "values": rowidList
    }
   ]
   const res = await callWorkflowListAPI('rkjhmxb', filters)
   if (res) {
    return res.data || {}
   }
}

// 获取入库计划单详情
const getTaskDetail = async (rowid) => {
  try {

    
    const res = await callWorkflowAPI('rkjhd', rowid)
    
    if (res) {
      console.log('详情页API响应数据', res)
      taskInfo.value = res || {}

      const rowidList = JSON.parse(taskInfo.value['6868c649c66aa1c3b15aff29']) || []
      console.log('收货单rowidList', rowidList);
      
      productInfo.value = await getProductInfo(rowidList)
      console.log('关联商品', productInfo.value);

    }
    

  } catch (error) {
    console.error('获取入库计划单详情失败:', error)
    uni.showToast({
      title: '获取详情失败',
      icon: 'error'
    })
  }
}

onLoad((options) => {
  const { rowid } = options
  getTaskDetail(rowid)
})

</script>

<style lang="scss" scoped>
.inbound-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
  
  // 信息块样式
  .info-block {
    background-color: #ffffff;
    margin: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .block-title {
      padding: 30rpx 30rpx 20rpx;
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      border-bottom: 2rpx solid #f0f0f0;
    }
    
    .info-content {
      padding: 20rpx 30rpx 30rpx;
      
      .product-item {
        padding: 20rpx 0;
        
        &:first-child {
          padding-top: 0;
        }
        
        &:last-child {
          padding-bottom: 0;
        }
      }
      
      .product-divider {
        height: 2rpx;
        background-color: #e0e0e0;
        margin: 20rpx 0;
      }
      
      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-label {
          color: #999999;
          font-size: 28rpx;
          min-width: 160rpx;
          flex-shrink: 0;
        }
        
        .info-value {
          color: #333333;
          font-size: 28rpx;
          flex: 1;
          margin-left: 20rpx;
        }
      }
    }
  }
  
  // 操作按钮
      .card-actions {
        position: fixed;
        display: flex;
        left: 0;
        right: 0;
        bottom: 0;          // 贴底
        justify-content: flex-end;
        align-items: center;
        background-color: #ffffff;
        width: 100%;
        height: 100rpx;
        
        .cancel-btn {
          padding: 10rpx 30rpx;
          margin-right: 10%;
          background-color: #ffffff;
          color: #87CEEB;
          border: 2rpx solid #87CEEB;
          border-radius: 15px;
          font-size: 26rpx;
        }
      }
}
</style>